#!/bin/bash

echo "========================================"
echo "    积分商城系统启动脚本"
echo "========================================"

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "❌ Java 未安装，请先安装 JDK 17+"
    exit 1
fi

# 检查Maven环境
if ! command -v mvn &> /dev/null; then
    echo "❌ Maven 未安装，请先安装 Maven"
    exit 1
fi

# 检查Node.js环境
if ! command -v node &> /dev/null; then
    echo "❌ Node.js 未安装，请先安装 Node.js 14+"
    exit 1
fi

echo "✅ 环境检查通过"

# 编译后端服务
echo "🔨 编译后端服务..."
mvn clean compile -DskipTests

if [ $? -ne 0 ]; then
    echo "❌ 后端编译失败"
    exit 1
fi

echo "✅ 后端编译成功"

# 启动买家服务
echo "🚀 启动买家服务..."
cd buyer-service
mvn spring-boot:run > ../logs/buyer-service.log 2>&1 &
BUYER_PID=$!
echo "买家服务PID: $BUYER_PID"
cd ..

# 等待服务启动
sleep 10

# 启动商家服务
echo "🚀 启动商家服务..."
cd seller-service
mvn spring-boot:run > ../logs/seller-service.log 2>&1 &
SELLER_PID=$!
echo "商家服务PID: $SELLER_PID"
cd ..

# 等待服务启动
sleep 10

# 启动网关服务
echo "🚀 启动网关服务..."
cd gateway-service
mvn spring-boot:run > ../logs/gateway-service.log 2>&1 &
GATEWAY_PID=$!
echo "网关服务PID: $GATEWAY_PID"
cd ..

echo ""
echo "========================================"
echo "🎉 后端服务启动完成!"
echo "========================================"
echo "服务状态："
echo "- 买家服务: http://localhost:8081 (PID: $BUYER_PID)"
echo "- 商家服务: http://localhost:8082 (PID: $SELLER_PID)"
echo "- 网关服务: http://localhost:8080 (PID: $GATEWAY_PID)"
echo ""
echo "📝 重要提醒："
echo "1. 请确保以下服务已启动："
echo "   - Nacos (localhost:8848)"
echo "   - Redis (localhost:6379)"
echo "   - MySQL (localhost:3306)"
echo "   - RocketMQ (localhost:9876)"
echo "   - MinIO (localhost:9000)"
echo ""
echo "2. 请先执行 database_design.sql 初始化数据库"
echo ""
echo "3. 要启动前端，请在另一个终端执行："
echo "   cd frontend"
echo "   npm install"
echo "   npm run serve"
echo ""
echo "按 Ctrl+C 停止所有服务"
echo "========================================"

# 等待用户中断
trap "echo '🛑 正在停止服务...'; kill $BUYER_PID $SELLER_PID $GATEWAY_PID 2>/dev/null; exit" INT
wait
